export class Code {
	/**
	 * 字符串替换占位符,方便拼接新的提示字符串
	 */
	public static readonly MSG_PARAM_PLACEHOLDER = "{}";
	/**
	 * 全局替换正则
	 */
	private static readonly REG_MSG_PARAM_PLACEHOLDER = new RegExp(
		Code.MSG_PARAM_PLACEHOLDER,
		"g"
	);
	/**
	 * 消息编码,用于国际化翻译
	 */
	private msgCode: string;
	/**
	 * 默认消息
	 */
	private msgDefault: string;
	/**
	 * 占位符参数
	 */
	private msgParams?: string[];
	/**
	 * 异常信息
	 */
	private error?: Error;

	constructor(
		msgCode: string,
		msgDefault: string,
		msgParams?: string[],
		error?: Error
	) {
		this.msgCode = msgCode;
		this.msgDefault = msgDefault;
		this.msgParams = msgParams;
		this.error = error;
	}

	public getMsgCode(): string {
		return this.msgCode;
	}

	public getMessage(message: string): string {
		if (!message) {
			return "unkown message";
		}
		if (!this.msgParams) {
			return message;
		}
		for (let p of this.msgParams) {
			if (!p) {
				p = "";
			}
			message = message.replace(Code.MSG_PARAM_PLACEHOLDER, p);
		}
		message = message.replace(Code.REG_MSG_PARAM_PLACEHOLDER, "");
		return message;
	}

	public getMsgDeault(): string {
		return this.getMessage(this.msgDefault);
	}

	public getError(): Error {
		let err = this.error;
		if (!err) {
			err = new Error(MSG_CODE_ERR_UNKOWN);
		}
		return err;
	}
}
/**
 * 常用msgcode
 */
export const MSG_CODE_SUCC = "succ";
export const MSG_CODE_ERR_UNKOWN = "err.unknown";
export const MSG_CODE_ERR_INTERNAL = "err.internal";
export const MSG_CODE_ERR_PARAMS = "err.params";
export const MSG_CODE_ERR_UNSUPPORT = "err.unsupport";
/**
 * 常用Code
 */
export const CODE_SUCC = new Code(MSG_CODE_SUCC, "执行成功");
export const CODE_ERROR_UNKNOWN = new Code(MSG_CODE_ERR_UNKOWN, "未知错误");
export const CODE_ERROR_INTERNAL = new Code(MSG_CODE_ERR_INTERNAL, "内部错误");
export const CODE_ERROR_PARAMS = new Code(MSG_CODE_ERR_PARAMS, "无效的参数");
export const CODE_ERROR_UNSUPPORT = new Code(
	MSG_CODE_ERR_UNSUPPORT,
	"功能暂不支持"
);
